import { Injectable } from '@angular/core';
import { QuoteBasic } from 'service/QuoteBasic';

import { IEMAService } from 'interface/IEMAService';

@Injectable()
export class EMAService implements IEMAService {

  connection;

  constructor() {

  }

  compute(quote:QuoteBasic, day:number):Array<any> {
    const emaList = [];
    const count = quote.close.length;
    const x = 2.0 / (day + 1);
    if(day > 0){
      for (let i=0; i<count; i++) {
        if (i == 0) {
          emaList.push(quote.close[i])
          continue;
        }
        const ema = x*quote.close[i] + (1-x)*emaList[i-1];
        emaList.push(parseFloat(ema.toFixed(4)));
      }
    }
    return emaList;
  }

  update(quote:QuoteBasic, day:number, oldList:Array<any>):Array<any> {
    const orignCount = quote.close.length;
    const oldCount = oldList.length;

    if(day > 0 && orignCount > 0){
      const x = 2.0 / (day + 1);

      if (orignCount === 1) {
        if (oldList.length === 0) {
          oldList.push(quote.close[0]);
        } else {
          oldList[0] = quote.close[0];
        }
        return oldList;
      } else if (oldCount === 0) {
        return this.compute(quote, day);
      }

      if (orignCount === oldCount) {
        oldList[oldCount-1] = parseFloat((x*quote.close[oldCount-1] + (1-x)*oldList[oldCount-2]).toFixed(4));
      } else {
        let addCount = orignCount -oldCount;
        for (let i = 0; i < addCount; i++) {
          const d = parseFloat((x*quote.close[orignCount-1-i] + (1-x)*oldList[orignCount-2-i]).toFixed(4));
          oldList.push(d);
        }
      }
    }

    return oldList;
  }
}
